//
//  GTVideoView.m
//  SampleApp2
//
//  Created by GXHC on 2023/6/19.
//

#import <AVFoundation/AVFoundation.h>
#import <UIKit/UIKit.h>
#import "GTVideoPlayer.h"

@interface GTVideoPlayer ()
@property (nonatomic, strong, readwrite) AVPlayerItem *videoItem;
@property (nonatomic, strong, readwrite) AVPlayer *avPlayer;
@property (nonatomic, strong, readwrite) AVPlayerLayer *playerLayer;

@end

@implementation GTVideoPlayer
+(GTVideoPlayer *)Player{
	static GTVideoPlayer *player;
	static dispatch_once_t onceToken;
	dispatch_once(&onceToken, ^{
		player = [[GTVideoPlayer alloc]init];
	});
	return player;
}

- (void)dealloc{
	
}


- (void)playWithVideoUrl:(NSString *)videoUrlString attachView:(UIView *)attachView {
	[self _stopPlay];
    NSURL *videoUrl = [NSURL URLWithString:videoUrlString];
    AVAsset *asset = [AVAsset assetWithURL:videoUrl];

    self.videoItem = [AVPlayerItem playerItemWithAsset:asset];
    [self.videoItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    [self.videoItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    CMTime duration = self.videoItem.duration;
    CGFloat videoDuration = CMTimeGetSeconds(duration);
    NSLog(@"%@", @(videoDuration));


    self.avPlayer = [AVPlayer playerWithPlayerItem:self.videoItem];
    [self.avPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 1)
                                                queue:dispatch_get_main_queue()
                                           usingBlock:^(CMTime time) {
        NSLog(@"播放进度: %@", @(CMTimeGetSeconds(time)));
    }];

    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer];
    self.playerLayer.frame = attachView.bounds;
    [attachView.layer addSublayer:self.playerLayer];
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_handlePlayEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];

}

- (void)_stopPlay {
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	
    [self.playerLayer removeFromSuperlayer];
    self.videoItem = nil;
    self.avPlayer = nil;
	
	[self.videoItem removeObserver:self forKeyPath:@"status"];
	[self.videoItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
}

- (void)_handlePlayEnd {
    [self.avPlayer seekToTime:CMTimeMake(0, 1)];
    [self.avPlayer play];
}

#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey, id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"status"]) {
        if (((NSNumber *)[change objectForKey:NSKeyValueChangeNewKey]).integerValue == AVPlayerStatusReadyToPlay) {
            [self.avPlayer play];
        } else {
            NSLog(@"");
        }
    } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        NSLog(@"缓冲: %@", [change objectForKey:NSKeyValueChangeNewKey]);
    }
}

@end
